<template>
  <div class="user-edit">
    <!-- Drawer抽屉 -->
    <Drawer
      :title="title"
      v-model="visible"
      width="720"
      draggable
      :mask-closable="type == '0'"
    >
      <div :style="{ maxHeight: maxHeight }" class="drawer-content">
        <div class="drawer-header">
          <!-- <div style="margin-right: 16px">基本信息</div> -->
          <Avatar :src="form.avatar" size="large" v-show="type != '2'" />
        </div>
        <Form label-colon v-show="type != '2'">
          <Row :gutter="32">
            <Col span="12">
              <FormItem label="用户ID">
                {{ form.id }}
                <Tooltip trigger="hover" placement="right" content="账户已禁用">
                  <Icon
                    v-show="form.status == -1"
                    type="md-lock"
                    size="18"
                    style="margin-left: 10px; cursor: pointer"
                  />
                </Tooltip>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="登录账号">
                {{ form.username }}
                <Tooltip
                  trigger="hover"
                  placement="right"
                  :content="`密码强度：${form.passStrength}`"
                >
                  <Icon
                    v-show="form.passStrength"
                    type="md-key"
                    :color="passColor"
                    size="18"
                    style="margin-left: 10px; cursor: pointer"
                  />
                </Tooltip>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <Form
          ref="form"
          :model="form"
          :rules="formValidate"
          label-position="top"
        >
          <Row :gutter="32" v-if="type == '2'">
            <Col span="12">
              <FormItem label="登录账号" prop="username">
                <Input
                  v-model="form.username"
                  autocomplete="off"
                  :maxlength="16"
                />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="密码" prop="password">
                <SetPassword v-model="form.password" @on-change="changePass" />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="32">
          
            <Col span="12">
              <FormItem label="用户类型" prop="userType">
                <Input disabled v-model="drivers" transfer placeholder="驾驶员">
                </Input>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="32">
            <Col span="12">
              <!-- <FormItem label="用户类型" prop="userType">
                <Input disabled v-model="drivers" transfer placeholder="驾驶员">
                </Input>
              </FormItem> -->

              <!-- <FormItem label="验证码" prop="mobile">
                <div style="display: flex">
                  <div>
                    <Input
                      style="width: 115%"
                      placeholder="请输入车老板手机号验证码"
                      v-model="form.mobile"
                    />
                  </div>
                  <div style="margin-left: 40px;">
                    <CountDownButton
                      ref="countDown"
                      @on-click="checkVaptcha"
                      :autoCountDown="false"
                      size="default"
                      :loading="sending"
                      :text="getSms"
                    />
                  </div>
                </div>
              </FormItem> -->
            </Col>
          </Row>
          <Divider />
        </Form>
      </div>
      <div class="drawer-footers br" v-show="type != '0'">
        <Button type="primary" :loading="submitLoading" @click="submit"
          >提交注册</Button
        >
        <Button style="margin-left: 10px" @click="visible = false">取消</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
import {
  getAllRoleList,
  adddriver,
  sendRegistSms,
  vaptchaID,
  vaptchaOffline,
  getdriverPage,
  getActualdriverPage
} from "@/api/index";
import {
  validateUsername,
  validateMobile,
  validatePassword,
} from "@/libs/validate";
import departmentTreeChoose from "@/views/my-components/freight/department-tree-choose";
import uploadPicInput from "@/views/my-components/freight/upload-pic-input";
import SetPassword from "@/views/my-components/freight/set-password";
import CountDownButton from "@/views/my-components/freight/count-down-button";
export default {
  name: "user",

  components: {
    departmentTreeChoose,
    uploadPicInput,
    SetPassword,
    CountDownButton,
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
    },
    type: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      getSms: "获取验证码",
      visible: this.value,
      title: "",
      passColor: "",
      submitLoading: false,
      maxHeight: 510,
      drivers: "驾驶员",
      form: {
        userType: "",
        username: "",
        password: "",
        bindingmobile: "",
      },
      driverData: {},
      getUnboundDriver: [],
      formValidate: {
        // 表单验证规则
        username: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
          { validator: validateUsername, trigger: "blur" },
        ],

        bindingmobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validateUsername, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePassword, trigger: "blur" },
        ],
        // email: [
        //   { required: true, message: "请输入邮箱地址" },
        //   { type: "email", message: "邮箱格式不正确" },
        // ],
        userType: [
          {
            required: true,
            type: "number",
            message: "请选择用户类型",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    initVaptcha() {
      let that = this;
      vaptcha({
        //配置参数
        vid: vaptchaID, // 验证单元id
        type: "invisible", // 展现类型 隐藏式
        offline_server: vaptchaOffline, // 离线验证接口地址 可选但此处不能为空
      }).then(function (vaptchaObj) {
        // vaptchaObject = vaptchaObj;
        vaptchaObj.listen("pass", function () {
          that.form.token = vaptchaObj.getToken();
          // 验证成功 发送验证码
          that.sendSmsCode();
        });
      });
    },
    checkVaptcha() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // vaptchaObject.validate(); // 若没验证验证码 开始验证
          this.sendSmsCode();
        }
      });
    },
    sendSmsCode() {
      this.form.captchaId = this.captchaId;
      let data = {
        code: this.form.imgCode,
        captchaId: this.form.captchaId,
      };
      this.sending = true;
      this.getSms = "发送中";
      sendRegistSms(this.form.mobile, data).then((res) => {
        this.getSms = "获取验证码";
        this.sending = false;
        // vaptchaObject.reset();
        if (res.success) {
          this.$Message.success("发送短信验证码成功");
          // 开始倒计时
          this.$refs.countDown.startCountDown();
        }
      });
    },
    init() {
      this.getRoleList();
    },
    // 添加驾驶员输入框编辑
    changeDriver(val) {
      if (val) {
        let text = /^[\u4e00-\u9fa5]{0,}$/;
        let reg = /^[1-9]\d*$/;
        if (text.test(val)) {
          if (val.length > 1) {
            this.$set(this.driverData, "searchContent", val);
            this.getDriver();
          }
        }
        if (reg.test(val)) {
          if (val.length > 3) {
            this.$set(this.driverData, "searchContent", val);
            this.getDriver();
          }
        }
      }
    },
    //获取未绑定驾驶员列表接口
    getDriver() {
      getActualdriverPage(this.driverData).then((res) => {
        if (res.code == 200) {
          this.driverData.searchContent = "";
          this.getUnboundDriver = res.result;
        } else {
          this.$Message.error(res.message);
        }
      });
    },

    getRoleList() {
      getAllRoleList().then((res) => {
        if (res.success) {
          this.roleList = res.result;
        }
      });
    },
    handleSelectDepTree(v) {
      this.form.departmentId = v;
    },
    changePass(v, grade, strength) {
      this.form.passStrength = strength;
    },
    submit() {
      this.form.userType = 1;
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (typeof this.form.birth == "object") {
            this.form.birth = this.format(this.form.birth, "yyyy-MM-dd");
          }
          // 添加
          this.submitLoading = true;
          this.form.avatar = "";
          this.form.mobile = this.form.username;
          adddriver(this.form).then((res) => {
            this.submitLoading = false;
            if (res.success) {
              this.$Message.success("新增成功");
              this.$emit("on-submit", true);
              this.visible = false;
            }
          });
        }
      });
    },
    setCurrentValue(value) {
      if (value === this.visible) {
        return;
      }
      if (this.type == "1") {
        this.title = "编辑用户";
        this.maxHeight =
          Number(document.documentElement.clientHeight - 121) + "px";
      } else if (this.type == "2") {
        this.title = "添加用户";
        this.maxHeight =
          Number(document.documentElement.clientHeight - 121) + "px";
      } else {
        this.title = "用户详情";
        this.maxHeight = "100%";
      }
      // 清空数据
      this.$refs.form.resetFields();
      if (this.type == "0" || this.type == "1") {
        // 回显数据
        let data = this.data;
        // 地址
        if (data.address) {
          data.address = data.address.split(",");
        } else {
          data.address = [];
        }
        // 部门
        // this.$refs.depTree.setData(data.departmentId, data.departmentTitle);
        // 角色
        let selectRolesId = [];
        data.roles.forEach(function (e) {
          selectRolesId.push(e.id);
        });
        data.roleIds = selectRolesId;
        delete data.roles;
        delete data.permissions;
        // 密码强度
        if (data.passStrength == "弱") {
          this.passColor = "#ed3f14";
        } else if (data.passStrength == "中") {
          this.passColor = "#faad14";
        } else if (data.passStrength == "强") {
          this.passColor = "#52c41a";
        }
        // 回显
        this.form = data;
      } else {
        // 添加
        // this.$refs.depTree.setData("", "");
        this.form = {
          type: 0,
          sex: "",
          address: [],
        };
      }
      this.visible = value;
    },
  },
  watch: {
    value(val) {
      this.setCurrentValue(val);
    },
    visible(value) {
      this.$emit("input", value);
    },
  },
  mounted() {
    this.init();
    // this.initVaptcha();
  },
};
</script>

<style lang="less">
@import "../../../styles/drawer-common.less";
.drawer-footers {
  z-index: 10;
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0 !important;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  background: #fff;
}
</style>

